<template>
	<view style="width: 100%;">
		<view class="u-page">
			<u-toast ref="uToast"></u-toast>
			<u-loading-page :loading="loading" bg-color="#e8e8e8"></u-loading-page>

			<u-row customStyle="margin: 10px">
				<u-col span="3">
					<!-- <u-button type="primary" icon="reload" @click="getList" shape="circle" text="刷新状态">
					</u-button> -->
				</u-col>
				<u-col span="3"></u-col>
				<!-- <u-col span="2">
					<view class="u-slot-title">
						<u-tag v-show='!serviceApply.startTime' text="未签到" plain type="warning"></u-tag>
						<u-tag v-show='serviceApply.startTime' text="已签到" plain type="success"></u-tag>
					</view>
				</u-col> -->
				<u-col span="1"></u-col>
				<u-col span="3">
					<!-- <u-button type="primary" style="text-align: right;" icon="map" shape="circle"
						@click="handel_sign_click" text="签到"></u-button> -->
				</u-col>
			</u-row>

			<!-- <u-row customStyle="margin: 10px">
				<u-col span="3">
					<u-button type="primary" icon="reload" @click="getList" shape="circle" text="刷新状态">
					</u-button>
				</u-col>
				<u-col span="6">
					<u--text text="签到状态:"></u--text>
					<u--text v-show='!serviceApply.startTime' type="error" text="未签到"></u--text>
					<u--text v-show='serviceApply.startTime' type="success" text="已签到"></u--text>
				</u-col>
				<u-col span="3">
					<u-button type="primary" style="text-align: right;" icon="map" shape="circle"
						@click="handel_sign_click" text="签到"></u-button>
				</u-col>
			</u-row> -->

			<u-modal width="450rpx" :show="show_signing" :show-close="false" :showConfirmButton="false">
				<view class="slot-content">
					<u-loading-icon mode="circle" text="签到中" textSize="18"></u-loading-icon>
				</view>
			</u-modal>

			<!-- <u-modal :show="show_outsideReason" title="定位超出范围" @confirm="handle_outsideReason_confirm">
				<view class="slot-content">
					<view class="slot-content">
						<u--textarea v-model="serviceApply.attribute1" placeholder="请填写定位超出范围原因,用于记录,不能为空"
							maxlength="50"></u--textarea>
					</view>
				</view>
			</u-modal> -->

			<!-- <u-row customStyle="margin: 5px">
				<u-col span="10">
					<u-search style="z-index: 999;" :disabled='true' bgColor="rgb(255 255 255)" placeholder="搜索"
						shape="round" @click="handle_SearchBox_click" :showAction="false" :animation="true"></u-search>
				</u-col>
				<u-col span="2">
					<u-button type="primary" icon="reload" @click="handleReflashClick" size="small" shape="circle"
						text="连接">
					</u-button>
				</u-col>
			</u-row> -->

			<!-- <u-popup :show="show" @close="close" @open="open">
				<view style="width: 93%;align-self: center;">
					<u--form labelWidth='auto' labelPosition="left" :model="queryParamsForm" :rules="rules" ref="form1">
						<u-form-item label="申请人姓名" prop="name" borderBottom ref="item1">
							<u--input inputAlign='center' shape='square' border="none" v-model="queryParamsForm.name">
							</u--input>
						</u-form-item>
						<u-form-item label="申请人身份证号码" prop="idNumber" borderBottom ref="item1">
							<u--input inputAlign='center' shape='square' border="none"
								v-model="queryParamsForm.idNumber">
							</u--input>
						</u-form-item>
					</u--form>
					<u-row customStyle="margin:10px">
						<u-col span="12">
							<u-button class="custom-style" type="primary" size="small" @click="handel_search_click">搜索
							</u-button>
						</u-col>
					</u-row>
					<u-row customStyle="margin:10px">
						<u-col span="12">
							<u-button class="custom-style" type="primary" size="small" @click="handel_reset_click">重置
							</u-button>
						</u-col>
					</u-row>
				</view>
			</u-popup> -->

			<u-row customStyle="margin-bottom: 10px ">
				<u-col span="12">
					<u-empty v-if="DataList.length == 0" mode="list"></u-empty>
					<u-cell-group customStyle='background-color: white;' v-else>
						<u-cell v-for="(item, index) in DataList" :key="item.assignId" size="large" isLink clickable
							@click="handel_cell_click" :name="item.assignDetailId">
							<view slot="title" class="u-slot-title">
								<text class="u-cell-text">{{ item.paperName }}</text>
								<u-tag v-if="item.status == '1'" text="答题完成" plain size="mini" type="success">
								</u-tag>
								<u-tag v-else-if="item.status == '0'" text="待答题" color="#C6C7CB" borderColor="#C6C7CB"
									plain size="mini">
								</u-tag>
							</view>
						</u-cell>
					</u-cell-group>
					<uni-load-more :status="status" :contentText="loadText" @clickLoadMore="MyonLoad" />
				</u-col>
			</u-row>
		</view>
	</view>
</template>

<script>
	import {
		listAssignDetail,
		getAssignDetail,
		delAssignDetail,
		addAssignDetail,
		updateAssignDetail
	} from "@/api/elder/questionnaire/assignDetail";
	import {
		listPaper
	} from "@/api/elder/questionnaire/paper";

	export default {
		name: "GZSG_index",
		components: {},
		data() {
			return {
				// 遮罩层
				loading: true,
				// 选中数组
				ids: [],
				// 总条数
				total: 0,
				// 发起问卷明细表格数据
				DataList: [],
				// 弹出层标题
				title: "",
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					assignId: null,
					value: null,
					level: null,
					required: null,
					status: null,
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {},

				checkIn: false, //自动签到
				show_signing: false, //签到窗口
				id: null,
				// 查询参数
				loading: false, //加载中提示框显示
				show: false, //搜索框显示
				finished: false, //加载更多完结
				loadText: {
					contentdown: "点击加载更多",
					contentrefresh: "正在加载",
					contentnomore: "没有更多数据了",
				},

				location: null, //位置信息字符串
				targetDistance: 5, //限制定位与用户登记位置的最大误差距离（千米）
				Distance: 0,
				signStatu: '', //签到状态，成功，失败
				show_outsideReason: false, //超范围原因框
				isOutside: false, //是否超出范围

				assignId: null,
				onLoadDone: false,
				paperOptions: [],
			}
		},
		watch: {},
		computed: {
			getItemLabel() {
				return function(item) {
					let result = "";
					if (item.status) result += item.status
					// if (item.status) result += item.status + ':'
					// if (item.taskStarttime) result += item.taskStarttime
					// if (item.taskEndtime) result += '-' + item.taskEndtime
					return result
				}
			},
			status() {
				if (this.DataList.length < this.total) {
					return "more";
				} else {
					this.finished = true;
					return "nomore";
				}
			},
		},
		onLoad: function(options) {
			console.log('options', options);
			this.assignId = options.assignId
			this.queryParams.assignId = options.assignId
		},
		onShow() {
			//同步等待onLoadDone，直到为true才执行
			this.finished = false; //重置搜索完结
			this.queryParams.pageNum = 1; //重置搜索页
			this.getList();
		},
		methods: {
			/** 查询发起问卷明细列表 */
			getList() {
				this.loading = true;
				listAssignDetail(this.queryParams).then(response => {
					//将response.rows每一项添加一个paperName和paperGroup属性，通过this.paperOptions的paperId找到对应的paperName和paperGroup
					console.log('listAssignDetail', response);
					if (response.rows.length > 0) {
						response.rows.forEach(item => {
							this.paperOptions.forEach(paper => {
								if (item.paperId == paper.paperId) {
									item.paperName = paper.paperName;
									item.paperGroup = paper.paperGroup;
								}
							});
						});
						this.DataList = response.rows;
						this.total = response.total;
						this.loading = false;
					}
				});
			},
			getOptions() {
				listPaper({
					pageNum: 1,
					pageSize: 1000,
				}).then(response => {
					console.log('getOptions', response);
					this.paperOptions = response.rows;
				});
			},
			// 取消按钮
			cancel() {
				this.open = false;
				this.reset();
			},
			// 表单重置
			reset() {
				this.form = {
					assignDetailId: null,
					assignId: null,
					orderNum: null,
					value: null,
					level: null,
					required: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					remark: null,
					spare1: null,
					spare2: null,
					spare3: null
				};
				this.resetForm("form");
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.resetForm("queryForm");
				this.handleQuery();
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.assignDetailId)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			/** 新增按钮操作 */
			handleAdd() {
				this.reset();
				this.open = true;
				this.title = "添加发起问卷明细";
			},
			/** 修改按钮操作 */
			handleUpdate(row) {
				this.reset();
				const assignDetailId = row.assignDetailId || this.ids
				getAssignDetail(assignDetailId).then(response => {
					this.form = response.data;
					this.open = true;
					this.title = "修改发起问卷明细";
				});
			},
			/** 提交按钮 */
			submitForm() {
				this.$refs["form"].validate(valid => {
					if (valid) {
						if (this.form.assignDetailId != null) {
							updateAssignDetail(this.form).then(response => {
								this.$modal.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addAssignDetail(this.form).then(response => {
								this.$modal.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			/** 删除按钮操作 */
			handleDelete(row) {
				const assignDetailIds = row.assignDetailId || this.ids;
				this.$modal.confirm('是否确认删除发起问卷明细编号为"' + assignDetailIds + '"的数据项？').then(function() {
					return delAssignDetail(assignDetailIds);
				}).then(() => {
					this.getList();
					this.$modal.msgSuccess("删除成功");
				}).catch(() => {});
			},
			/** 导出按钮操作 */
			handleExport() {
				this.download('elder/questionnaire/assignDetail/export', {
					...this.queryParams
				}, `assignDetail_${new Date().getTime()}.xlsx`)
			},
			handle_ratingChange(value) {
				// this.form.level = value;
			},
			//跳转回答页面
			handle_answer(row) {
				console.log('handle_answer', row);
				//URl传参跳转
				this.$router.push({
					name: `Answer`,
					params: {
						assignDetailId: row
							.assignDetailId //这种传参方式，不是在url中传参，而是在路由的params中传参，所以在跳转的时候，需要在路由中配置name和params
					},
				});
			},
			MyonLoad(e) {
				this.fetch();
				this.finished = true;
				e.detail = {
					status: "loading",
				};
				return e;
			},
			//签到
			handel_sign_click() {
				if (this.isOutside) {
					this.show_outsideReason = true;
					return;
				}
				this.show_signing = true;
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					isHighAccuracy: true,
					success: (res) => {
						this.show_signing = false;
						this.location = (res.address.province + res.address.city + res.address
							.district + res.address.street + res.address.streetNum + res
							.address.poiName)
						this.serviceApply.realLatitude = res.latitude
						this.serviceApply.realLongitude = res.longitude
						// this.signLocation.latitude = res.latitude
						// this.signLocation.longitude = res.longitude
						//比较目标距离(需要申请人信息)
						let Distance = GetDistance(this.serviceApply.taskLatitude, this.serviceApply
							.taskLongitude, this.serviceApply.realLatitude, this.serviceApply
							.realLongitude
						)
						this.Distance = Distance * 1000
						this.signStatu = "成功";
						this.updateSignLocationAndReason();
						// if (Distance <= this.targetDistance) {
						// 	//距离内
						// 	this.signStatu = "成功";
						// 	this.updateSignLocationAndReason();
						// 	this.$refs.uToast.show({
						// 		type: 'success',
						// 		message: "签到成功",
						// 		iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
						// 		complete() {}
						// 	})
						// } else {
						// 	//超出距离,需要填写理由
						// 	this.show_outsideReason = true;
						// 	//签到时间传入作为改造开始时间的默认值/或者签到直接更新每一个的改造开始时间
						// }
					},
					fail: (res) => {
						console.log('定位失败：' + res);
						this.signStatu = "失败";
						this.$refs.uToast.show({
							type: 'fail',
							message: "定位失败：" + res,
							complete() {}
						})
						this.location = '定位失败,请检查设备定位权限是否开启'
					},
				});
			},
			// //填写原因确认框
			// handle_outsideReason_confirm() {
			// 	if (!this.serviceApply.attribute1) {
			// 		this.$refs.uToast.show({
			// 			type: 'error',
			// 			message: "原因不能为空",
			// 			iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/error.png',
			// 			complete() {}
			// 		})
			// 		return
			// 	}
			// 	this.show_outsideReason = false
			// 	this.signStatu = "成功";
			// 	this.updateSignLocationAndReason();
			// 	this.$refs.uToast.show({
			// 		type: 'success',
			// 		message: "签到成功",
			// 		iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
			// 		complete() {}
			// 	})
			// },
			//更新签到地点和理由
			updateSignLocationAndReason() {
				this.serviceApply.planStartTime = GetDatetime();
				let partParmeter = {
					"id": this.serviceApply.id,
					"realLatitude": this.serviceApply.realLatitude,
					"realLongitude": this.serviceApply.realLongitude,
					//"attribute1": this.serviceApply.attribute1,
					"attribute2": this.Distance,
					"startTime": this.serviceApply.planStartTime
				}
				updateSlhgzresqjl(partParmeter).then((response) => {
					if (response.code == 200) {
						this.$refs.uToast.show({
							type: 'success',
							message: "签到成功",
							iconUrl: 'https://cdn.uviewui.com/uview/demo/toast/success.png',
							complete() {}
						})
						//更新信息-签到状态
						getSlhgzresqjl(this.id).then((response) => {
							this.queryParams.taskId = response.data.taskId //将老人id保存
							this.serviceApply = response.data
						});
					} else {
						this.$refs.uToast.show({
							type: 'fail',
							message: "签到失败",
							complete() {}
						})
					}
				});
			},
			handel_cell_click(item) {
				//跳转题目页，传输assignId（考试）,assignDetailId(哪张考卷)
				this.$tab.navigateTo('/pages/WenJuanDiaoCha/Answer/index?assignId=' + this.assignId + '&assignDetailId=' +
					item.name)
			},
			fetch() {
				this.queryParams.pageNum = this.queryParams.pageNum + 1;
				listAssignDetail(this.queryParams).then(response => {
					this.DataList = this.DataList.concat(response.rows);
					this.total = response.total;
					// this.update_connetStatus();
				});
			},
		},
	}
</script>

<style scoped>
	.custom-style {
		width: 90%;
		font-weight: bolder;
		font-size: 15px;
	}

	.u-slot-title {
		display: flex;
		align-items: center;
		/* 垂直居中 */
	}

	.u-cell-text {
		margin-right: 10px;
		/* 可根据需要调整元素间的间距 */
	}

	.slot-content {
		width: 90%;
		/* 自定义宽度 */
		margin: 0 auto;
		/* 水平居中 */
	}

	.status-col {
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}

	.status-wrapper {
		display: flex;
		align-items: center;
		justify-content: flex-end;
	}
</style>